<?php

namespace App\Jobs;

use App\Models\Category;
use App\Models\Member;
use App\Notifications\SysNotify;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Notification;

/**
 * 用户初始化 当新增用户的时候
 * 初始化账本
 * 初始化分类
 */
class UserInit implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $user_id;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($user_id)
    {
        $this->user_id = $user_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $user = Member::query()->find($this->user_id);
        if (is_null($user)) {
            return;
        }
        $pwd = mt_rand(100000, 999999);
        $user->password = bcrypt($pwd);
        $user->save();

        $notify = new SysNotify('密码初始化通知', '您的密码是:' . $pwd . ' 请尽快修改密码，该密码可用于APP登录，如有问题可联系开发者，QQ：2143767985，微信：xian_duo_duo', '请尽快修改密码');

        Notification::send($user, $notify);

        $cashbook =  $user->cashbooks()->create(
            [
                'user_id' => $user->id,
                'name' => '默认账本'
            ]
        );
        // 设置默认账本
        $user->update([
            'default_cashbook_id' => $cashbook->id
        ]);

        $items = Category::query()->where('user_id', 0)->get([
            'name',
            'type',
            'icon'
        ]);
        foreach ($items as $item) {
            $data = array_merge($item->toArray(), [
                'user_id' => $user->id
            ]);
            Category::query()->create($data);
        }
    }
}
